import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import styles from '../css/search.module.css';
import lefts from '../assets/left.png';
import { fetchStrategyData, fetchTravelData, fetchQuesData } from '../api/searchApi';
import { fetchScenicData} from '../api/scenicData';

const SearchPage = () => {
    const navigate = useNavigate();
    const [searchResults, setSearchResults] = useState([]);
    const [searchValue, setSearchValue] = useState('');
    const [dataSources, setDataSources] = useState({
        scenic: [],
        strategy: [],
        travel: [],
        question: []
    });

    // 初始化用户ID和获取数据
    useEffect(() => {
        const id = sessionStorage.getItem("userid");
        console.log("User ID:", id);
        
        // 获取所有数据
        const fetchAllData = async () => {
            try {
                const [
                    scenicResponse,
                    strategyResponse,
                    travelResponse,
                    quesResponse
                ] = await Promise.all([
                    fetchScenicData(),
                    fetchStrategyData(),
                    fetchTravelData(),
                    fetchQuesData()
                ]);

                setDataSources({
                    scenic: scenicResponse.data || [],
                    strategy: strategyResponse.data || [],
                    travel: travelResponse.data || [],
                    question: quesResponse.data || []
                });
            } catch (error) {
                console.error('获取数据时出错:', error);
            }
        };

        fetchAllData();

        // 禁止页面滚动
        document.body.style.overflow = 'hidden';
        return () => {
            document.body.style.overflow = 'auto';
        };
    }, []);

    // 返回上一页
    const left = () => navigate(-1);

    // 搜索功能
    const handleSearch = (e) => {
        const value = e.target.value;
        setSearchValue(value);

        if (!value.trim()) {
            setSearchResults([]);
            return;
        }

        const results = [];
        const { scenic, strategy, travel, question } = dataSources;

        // 搜索景区
        scenic.forEach(item => {
            if (String(item.name).includes(value)) {
                results.push({
                    ...item,
                    type: 1,
                    displayName: `景区-${item.name}`
                });
            }
        });

        // 搜索攻略
        strategy.forEach(item => {
            if (String(item.title).includes(value)) {
                results.push({
                    ...item,
                    type: 2,
                    displayName: `攻略-${item.title}`
                });
            }
        });

        // 搜索游记
        travel.forEach(item => {
            if (String(item.title).includes(value)) {
                results.push({
                    ...item,
                    type: 3,
                    displayName: `游记-${item.title}`
                });
            }
        });

        // 搜索问答
        question.forEach(item => {
            if (String(item.name).includes(value)) {
                results.push({
                    ...item,
                    type: 4,
                    displayName: `问答-${item.name}`
                });
            }
        });

        setSearchResults(results);
    };

    // 处理点击搜索结果项
    const handleItemClick = (item) => {
        const { type, id, title, name, banner } = item;
        const sessionData = {
            game: JSON.stringify(item),
            gameimg: banner || item.bannar
        };

        switch (type) {
            case 1: // 景区
                sessionStorage.setItem("jingid", id);
                sessionStorage.setItem("jingdata", sessionData.game);
                navigate("/scenicdetails");
                break;
            case 2: // 攻略
                sessionStorage.setItem("status", "1");
                Object.entries(sessionData).forEach(([key, val]) => 
                    sessionStorage.setItem(key, val)
                );
                navigate("/strategy");
                break;
            case 3: // 游记
                sessionStorage.setItem("status", "2");
                sessionStorage.setItem("playid", id);
                Object.entries(sessionData).forEach(([key, val]) => 
                    sessionStorage.setItem(key, val)
                );
                navigate("/strategys");
                break;
            case 4: // 问答
                sessionStorage.setItem("quesdata", sessionData.game);
                break;
        }
        
        setSearchValue('');
    };

    return (
        <div className={styles.big}>
            {/* 顶部搜索栏 */}
            <div className={styles.top}>
                <img
                    src={lefts}
                    alt="返回"
                    onClick={left}
                    className={styles.backButton}
                />
                <input
                    type="text"
                    placeholder="请输入景区或者用户名称"
                    className={styles.searchInput}
                    value={searchValue}
                    onChange={handleSearch}
                />
            </div>

            {/* 搜索结果列表 */}
            <div className={styles.item}>
                {searchResults.length > 0 ? (
                    searchResults.map((item, index) => (
                        <div
                            key={`${item.type}-${index}`}
                            className={styles.itemOne}
                            onClick={() => handleItemClick(item)}
                        >
                            <div className={styles.itemContent}>
                                <p className={styles.itemText}>{item.displayName}</p>
                            </div>
                        </div>
                    ))
                ) : (
                    searchValue && <p className={styles.noDataText}>暂无数据</p>
                )}
            </div>
        </div>
    );
};

export default SearchPage;